package me.tuyou.activiti.identityService;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.test.ActivitiRule;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

import java.util.List;

public class IdentityServiceTest {

    @Rule
    public ActivitiRule activitiRule = new ActivitiRule();

    /**
     * 测试用户创建和删除api
     */
    @Test
    public void createUser() {
        IdentityService service = activitiRule.getIdentityService();
        Assert.assertNotNull(service);
//        service.deleteUser("tuyou");

        User user = service.newUser("yangrui");
        user.setFirstName("yang");
        user.setLastName("rui");
        user.setEmail("yangrui@qq.com");

        service.saveUser(user);

//        user = service.createUserQuery().userId("tuyou").singleResult();
//        Assert.assertNotNull(user);
//
//        service.deleteUser("tuyou");
//
//        user = service.createUserQuery().userId("tuyou").singleResult();
//        Assert.assertNull(user);
    }

    /**
     * 测试组的创建和删除api
     */
    @Test
    public void createGroup() {
        IdentityService identityService = activitiRule.getIdentityService();
        Group adminGroup = identityService.newGroup("1");
        adminGroup.setName("管理员组");
        adminGroup.setType("admin");

        identityService.saveGroup(adminGroup);

        adminGroup = identityService.createGroupQuery().groupId("1").singleResult();
        Assert.assertNotNull(adminGroup);

        identityService.deleteGroup("1");
        adminGroup = identityService.createGroupQuery().groupId("1").singleResult();
        Assert.assertNull(adminGroup);
    }

    /**
     * 测试用户和组的关联关系
     */
    @Test
    public void userGroupRelation() {

        IdentityService identityService = activitiRule.getIdentityService();
        identityService.deleteUser("tuyou");
        identityService.deleteGroup("admin");

        User user = identityService.newUser("tuyou");
        user.setFirstName("tu");
        user.setLastName("you");
        user.setEmail("497122758@qq.com");
        identityService.saveUser(user);

        Group group = identityService.newGroup("admin");
        group.setName("管理员");
        identityService.saveGroup(group);

        //关联用户和组
        identityService.createMembership("tuyou", "admin");

        //查询组下面的所有用户
        List<User> userInGroup = identityService.createUserQuery().memberOfGroup("admin").list();
        Assert.assertNotNull(userInGroup);
        for (User item : userInGroup) {
            System.out.println(item.getId());
        }

        group = identityService.createGroupQuery().groupMember("tuyou").singleResult();
        Assert.assertNotNull(group);

        identityService.deleteUser("tuyou");
        identityService.deleteGroup("admin");
    }
}
